/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.bpm.engine.impl.scripting;

import com.je.bpm.engine.delegate.VariableScope;

import javax.script.Bindings;
import javax.script.SimpleScriptContext;
import java.util.*;

import static java.util.Arrays.asList;


public class ScriptBindings implements Bindings {

    /**
     * The script engine implementations put some key/value pairs into the binding.
     * This list contains those keys, such that they wouldn't be stored as process variable.
     * <p>
     * This list contains the keywords for JUEL, Javascript and Groovy.
     */
    protected static final Set<String> UNSTORED_KEYS =
            new HashSet<String>(asList("out", "out:print", "lang:import", "context", "elcontext", "print", "println", "nashorn.global"));

    protected List<Resolver> scriptResolvers;
    protected VariableScope variableScope;
    protected Bindings defaultBindings;
    protected boolean storeScriptVariables = true; // By default everything is stored (backwards compatibility)

    public ScriptBindings(List<Resolver> scriptResolvers, VariableScope variableScope) {
        this.scriptResolvers = scriptResolvers;
        this.variableScope = variableScope;
        this.defaultBindings = new SimpleScriptContext().getBindings(SimpleScriptContext.ENGINE_SCOPE);
    }

    public ScriptBindings(List<Resolver> scriptResolvers, VariableScope variableScope, boolean storeScriptVariables) {
        this(scriptResolvers, variableScope);
        this.storeScriptVariables = storeScriptVariables;
    }

    @Override
    public boolean containsKey(Object key) {
        for (Resolver scriptResolver : scriptResolvers) {
            if (scriptResolver.containsKey(key)) {
                return true;
            }
        }
        return defaultBindings.containsKey(key);
    }

    @Override
    public Object get(Object key) {
        for (Resolver scriptResolver : scriptResolvers) {
            if (scriptResolver.containsKey(key)) {
                return scriptResolver.get(key);
            }
        }
        return defaultBindings.get(key);
    }

    @Override
    public Object put(String name, Object value) {
        if (storeScriptVariables) {
            Object oldValue = null;
            if (!UNSTORED_KEYS.contains(name)) {
                oldValue = variableScope.getVariable(name);
                variableScope.setVariable(name, value);
                return oldValue;
            }
        }
        return defaultBindings.put(name, value);
    }

    @Override
    public Set<Entry<String, Object>> entrySet() {
        return variableScope.getVariables().entrySet();
    }

    @Override
    public Set<String> keySet() {
        return variableScope.getVariables().keySet();
    }

    @Override
    public int size() {
        return variableScope.getVariables().size();
    }

    @Override
    public Collection<Object> values() {
        return variableScope.getVariables().values();
    }

    @Override
    public void putAll(Map<? extends String, ? extends Object> toMerge) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Object remove(Object key) {
        if (UNSTORED_KEYS.contains(key)) {
            return null;
        }
        return defaultBindings.remove(key);
    }

    @Override
    public void clear() {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean containsValue(Object value) {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isEmpty() {
        throw new UnsupportedOperationException();
    }

    public void addUnstoredKey(String unstoredKey) {
        UNSTORED_KEYS.add(unstoredKey);
    }

}
